#include "spi.h"


void SpiConfig(void)
{
    spi_parameter_struct spi_init_struct;

    rcu_periph_clock_enable(RCU_SPI0);
    
    spi_i2s_deinit(SPI0);
    spi_struct_para_init(&spi_init_struct);

    /* SPI0 parameter config */
    spi_init_struct.trans_mode           = SPI_TRANSMODE_FULLDUPLEX;
    spi_init_struct.device_mode          = SPI_MASTER;
    spi_init_struct.frame_size           = SPI_FRAMESIZE_16BIT;
    spi_init_struct.clock_polarity_phase = SPI_CK_PL_HIGH_PH_2EDGE;
    spi_init_struct.nss                  = SPI_NSS_SOFT;
    spi_init_struct.prescale             = SPI_PSC_8;
    spi_init_struct.endian               = SPI_ENDIAN_MSB;
    spi_init(SPI0, &spi_init_struct);
	spi_enable(SPI0);	
    
}

static int spi_transmit_receive(uint16_t data_in, uint16_t *data_out){
	int state = 0;
	*data_out = 0;
	uint32_t timeout_cnt;
	static const uint32_t timeout_cnt_num = 10000;

	/* Wait until TXE flag is set to send data */
	timeout_cnt = 0;
	while(RESET == spi_i2s_flag_get(SPI0, SPI_FLAG_TBE)){
		timeout_cnt ++;
		if(timeout_cnt > timeout_cnt_num){
			state = -1;
			break;
		}
	}
	
	/* Transmit data in 16 Bit mode */
	spi_i2s_data_transmit(SPI0, data_in);
	
	/* Check BSY flag */
	timeout_cnt = 0;
	while(spi_i2s_flag_get(SPI0, SPI_FLAG_TRANS)){
		timeout_cnt ++;
		if(timeout_cnt > timeout_cnt_num){
			state = -1;
			break;
		}
	}
	
	/* Check RXNE flag */
	timeout_cnt = 0;
	while(RESET == spi_i2s_flag_get(SPI0, SPI_FLAG_RBNE)){
		timeout_cnt ++;
		if(timeout_cnt > timeout_cnt_num){
			state = -1;
			break;
		}
	}
	
	// Read 16-Bits in the data register
	*data_out = spi_i2s_data_receive(SPI0);
	
	return state;
}

void EnconderReadData(uint32_t *pos)
{
	uint16_t sampleData;
	uint8_t hCount;
	uint8_t pcFlag,noMagFlag;	/* 奇偶校验位  弱磁报警位 */
	uint16_t dataTx[2];
	uint16_t dataRx[2];
	
	dataTx[0] = (0x80 | 0x03) << 8;
	dataTx[1] = (0x80 | 0x04) << 8;
	
	gpio_bit_reset(GPIOC, GPIO_PIN_13);	
	spi_transmit_receive(dataTx[0],&dataRx[0]);								
	gpio_bit_set(GPIOC, GPIO_PIN_13);
				
	gpio_bit_reset(GPIOC, GPIO_PIN_13);		
	spi_transmit_receive(dataTx[1],&dataRx[1]);	
	gpio_bit_set(GPIOC, GPIO_PIN_13);	

	sampleData = ((dataRx[0] & 0x00FF) << 8) | (dataRx[1] & 0x00FF);

	for (uint8_t i = 0; i < 16; i++)
	{
		if(sampleData & 0x01<<i)
		{
			hCount++;
		}
	}

	if(hCount & 0x01)
	{
		pcFlag = 0;
	}
	else
	{
		pcFlag = 1;
	}
	
	if(pcFlag == 1)
	{
		*pos = sampleData >> 2;
		noMagFlag = (sampleData & (0x0001 << 1));
	}
}